<template>
  <div class="trade-manage">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <div>
          <h2>交易管理</h2>
          <p>管理系统中的所有交易记录</p>
        </div>
        <div class="header-actions">
          <el-button @click="exportData" :loading="exportLoading">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button type="primary" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" label-width="80px">
        <el-form-item label="交易ID">
          <el-input 
            v-model="searchForm.tradeid" 
            placeholder="请输入交易ID"
            clearable
            style="width: 160px"
          />
        </el-form-item>
        <el-form-item label="银行卡号">
          <el-input 
            v-model="searchForm.cardid" 
            placeholder="请输入银行卡号"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="交易类型">
          <el-select v-model="searchForm.tradetype" placeholder="请选择交易类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="存款" value="存款" />
            <el-option label="取款" value="取款" />
            <el-option label="转账" value="转账" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额范围">
          <el-input-number 
            v-model="searchForm.minAmount" 
            placeholder="最小金额" 
            :min="0" 
            :precision="2"
            style="width: 120px"
          />
          <span style="margin: 0 8px;">-</span>
          <el-input-number 
            v-model="searchForm.maxAmount" 
            placeholder="最大金额" 
            :min="0" 
            :precision="2"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item label="交易时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleExport" :loading="exportLoading">
            <el-icon><Download /></el-icon>
            导出CSV
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card deposit">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Plus /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.depositCount }}</div>
              <div class="stat-label">存款笔数</div>
              <div class="stat-amount">¥{{ stats.depositAmount.toLocaleString() }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card withdraw">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Minus /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.withdrawCount }}</div>
              <div class="stat-label">取款笔数</div>
              <div class="stat-amount">¥{{ stats.withdrawAmount.toLocaleString() }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card transfer">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Switch /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.transferCount }}</div>
              <div class="stat-label">转账笔数</div>
              <div class="stat-amount">¥{{ stats.transferAmount.toLocaleString() }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card total">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalCount }}</div>
              <div class="stat-label">总交易数</div>
              <div class="stat-amount">¥{{ stats.totalAmount.toLocaleString() }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 交易列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>交易记录列表</span>
          <div class="header-actions">
            <el-text type="info">共 {{ pagination.total }} 条记录</el-text>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="tradeList" 
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        empty-text="暂无交易记录"
      >
        <el-table-column prop="tradeid" label="交易ID" width="140" />
        <el-table-column prop="cardid" label="银行卡号" width="180">
          <template #default="{ row }">
            <span class="card-number">{{ formatCardNumber(row.cardid) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="tradetype" label="交易类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTradeTypeColor(row.tradetype)" size="small">
              {{ row.tradetype }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="trademoney" label="交易金额" width="140" sortable>
          <template #default="{ row }">
            <span :class="getAmountClass(row.tradetype)">
              ¥{{ Number(row.trademoney || 0).toLocaleString() }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="tradedate" label="交易时间" width="160" sortable>
          <template #default="{ row }">
            {{ formatDateTime(row.tradedate) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.remark || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 交易详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="交易详情"
      width="600px"
    >
      <div v-if="selectedTrade" class="trade-detail">
        <el-descriptions :column="2" border size="large">
          <el-descriptions-item label="交易ID">
            <el-text type="primary">{{ selectedTrade.tradeid }}</el-text>
          </el-descriptions-item>
          <el-descriptions-item label="银行卡号">
            <span class="card-number">{{ formatCardNumber(selectedTrade.cardid) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="交易类型">
            <el-tag :type="getTradeTypeColor(selectedTrade.tradetype)">
              {{ selectedTrade.tradetype }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="交易金额">
            <span :class="getAmountClass(selectedTrade.tradetype)" style="font-weight: bold; font-size: 16px;">
              ¥{{ Number(selectedTrade.trademoney || 0).toLocaleString() }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="交易时间">
            {{ formatDateTime(selectedTrade.tradedate) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedTrade.remark || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="printReceipt">
          <el-icon><Printer /></el-icon>
          打印凭条
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus,
  Minus,
  Switch,
  TrendCharts,
  View,
  Delete,
  Download,
  Printer
} from '@element-plus/icons-vue'
import { adminTradeApi } from '@/api/trade'
import { CSVExporter, tradeExportColumns } from '@/utils/csvExport'

export default {
  name: 'TradeManage',
  components: {
    Search,
    Refresh,
    Plus,
    Minus,
    Switch,
    TrendCharts,
    View,
    Delete,
    Download,
    Printer
  },
  setup() {
    const loading = ref(false)
    const exportLoading = ref(false)
    const detailDialogVisible = ref(false)
    const selectedTrade = ref(null)

    // 搜索表单
    const searchForm = reactive({
      tradeid: '',
      cardid: '',
      tradetype: '',
      minAmount: null,
      maxAmount: null
    })

    // 日期范围
    const dateRange = ref([])

    // 分页
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    // 交易列表
    const tradeList = ref([])

    // 统计数据
    const stats = reactive({
      depositCount: 0,
      depositAmount: 0,
      withdrawCount: 0,
      withdrawAmount: 0,
      transferCount: 0,
      transferAmount: 0,
      totalCount: 0,
      totalAmount: 0
    })

    // 获取交易列表
    const fetchTrades = async () => {
      loading.value = true
      try {
        // 构建查询参数 - 修复参数格式
        const queryData = {
          page: pagination.current,
          pageSize: pagination.size
        }

        // 添加搜索条件
        if (searchForm.tradeid) queryData.tradeid = searchForm.tradeid
        if (searchForm.cardid) queryData.cardid = searchForm.cardid
        if (searchForm.tradetype) queryData.tradetype = searchForm.tradetype
        if (searchForm.minAmount !== null) queryData.minAmount = searchForm.minAmount
        if (searchForm.maxAmount !== null) queryData.maxAmount = searchForm.maxAmount

        const [begin, end] = dateRange.value || []
        
        console.log('交易查询参数:', { queryData, begin, end })
        
        const response = await adminTradeApi.pageTrade(queryData, begin, end)
        
        console.log('交易查询响应:', response)
        
        if (response.code === 0) {
          tradeList.value = response.data?.records || []
          pagination.total = response.data?.total || 0
          
          // 计算统计数据
          calculateStats(tradeList.value)
        } else {
          ElMessage.error(response.msg || '获取交易列表失败')
          tradeList.value = []
          pagination.total = 0
          resetStats()
        }
      } catch (error) {
        console.error('获取交易列表失败:', error)
        ElMessage.error('获取交易列表失败')
        tradeList.value = []
        pagination.total = 0
        resetStats()
      } finally {
        loading.value = false
      }
    }

    // 计算统计数据
    const calculateStats = (trades) => {
      const depositTrades = trades.filter(t => t.tradetype === '存款')
      const withdrawTrades = trades.filter(t => t.tradetype === '取款')
      const transferTrades = trades.filter(t => t.tradetype === '转账')

      stats.depositCount = depositTrades.length
      stats.depositAmount = depositTrades.reduce((sum, t) => sum + Number(t.trademoney || 0), 0)
      
      stats.withdrawCount = withdrawTrades.length
      stats.withdrawAmount = withdrawTrades.reduce((sum, t) => sum + Number(t.trademoney || 0), 0)
      
      stats.transferCount = transferTrades.length
      stats.transferAmount = transferTrades.reduce((sum, t) => sum + Number(t.trademoney || 0), 0)
      
      stats.totalCount = trades.length
      stats.totalAmount = trades.reduce((sum, t) => sum + Number(t.trademoney || 0), 0)
    }

    // 重置统计数据
    const resetStats = () => {
      Object.assign(stats, {
        depositCount: 0,
        depositAmount: 0,
        withdrawCount: 0,
        withdrawAmount: 0,
        transferCount: 0,
        transferAmount: 0,
        totalCount: 0,
        totalAmount: 0
      })
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      fetchTrades()
    }

    // 重置
    const handleReset = () => {
      Object.assign(searchForm, {
        tradeid: '',
        cardid: '',
        tradetype: '',
        minAmount: null,
        maxAmount: null
      })
      dateRange.value = []
      pagination.current = 1
      fetchTrades()
    }

    // 刷新数据
    const handleRefresh = () => {
      fetchTrades()
    }

    // 查看详情
    const handleView = (row) => {
      selectedTrade.value = row
      detailDialogVisible.value = true
    }

    // 删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除交易记录 "${row.tradeid}" 吗？此操作不可恢复！`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await adminTradeApi.deleteTrade(row.tradeid)
        if (response.code === 0) {
          ElMessage.success('删除成功')
          fetchTrades()
        } else {
          ElMessage.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除交易记录失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 导出数据
    const exportData = async () => {
      exportLoading.value = true
      try {
        // 获取所有数据用于导出
        const exportParams = {
          page: 1,
          pageSize: pagination.total || 10000 // 导出所有数据
        }

        // 添加搜索条件
        if (searchForm.tradeid) exportParams.tradeid = searchForm.tradeid
        if (searchForm.cardid) exportParams.cardid = searchForm.cardid
        if (searchForm.tradetype) exportParams.tradetype = searchForm.tradetype
        if (searchForm.minAmount !== null) exportParams.minAmount = searchForm.minAmount
        if (searchForm.maxAmount !== null) exportParams.maxAmount = searchForm.maxAmount

        const [begin, end] = dateRange.value || []
        
        const response = await adminTradeApi.pageTrade(exportParams, begin, end)
        
        if (response.code === 0) {
          const exportData = response.data?.records || []
          
          if (exportData.length === 0) {
            ElMessage.warning('没有数据可导出')
            return
          }

          // 使用CSV导出工具
          const { CSVExporter, tradeExportColumns } = await import('@/utils/csvExport')
          CSVExporter.exportToCSV(exportData, tradeExportColumns, '交易记录')
          
          ElMessage.success(`成功导出 ${exportData.length} 条交易记录`)
        } else {
          ElMessage.error(response.msg || '获取导出数据失败')
        }
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      } finally {
        exportLoading.value = false
      }
    }

    // 打印凭条
    const printReceipt = () => {
      if (!selectedTrade.value) return
      
      const printContent = `
        <div style="text-align: center; font-family: Arial, sans-serif;">
          <h2>银行交易凭条</h2>
          <hr>
          <p><strong>交易ID:</strong> ${selectedTrade.value.tradeid}</p>
          <p><strong>交易类型:</strong> ${selectedTrade.value.tradetype}</p>
          <p><strong>银行卡号:</strong> ${formatCardNumber(selectedTrade.value.cardid)}</p>
          <p><strong>交易金额:</strong> ¥${Number(selectedTrade.value.trademoney || 0).toLocaleString()}</p>
          <p><strong>交易时间:</strong> ${formatDateTime(selectedTrade.value.tradedate)}</p>
          <p><strong>余额:</strong> ¥${Number(selectedTrade.value.balance || 0).toLocaleString()}</p>
          <hr>
          <p style="font-size: 12px;">此凭条仅作交易记录，请妥善保管</p>
        </div>
      `
      
      const printWindow = window.open('', '_blank')
      printWindow.document.write(printContent)
      printWindow.document.close()
      printWindow.print()
      printWindow.close()
    }

    // 导出CSV
    const handleExport = async () => {
      if (tradeList.value.length === 0) {
        ElMessage.warning('没有数据可导出')
        return
      }

      try {
        exportLoading.value = true
        CSVExporter.exportToCSV(tradeList.value, tradeExportColumns, '交易管理报表')
        ElMessage.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败: ' + error.message)
      } finally {
        exportLoading.value = false
      }
    }

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.current = 1
      fetchTrades()
    }

    const handleCurrentChange = (current) => {
      pagination.current = current
      fetchTrades()
    }

    // 工具函数
    const formatCardNumber = (cardNumber) => {
      if (!cardNumber) return ''
      return cardNumber.replace(/(\d{4})(?=\d)/g, '$1 ')
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }

    const getTradeTypeColor = (type) => {
      const colorMap = {
        '存款': 'success',
        '取款': 'warning',
        '转账': 'primary'
      }
      return colorMap[type] || 'info'
    }

    const getAmountClass = (type) => {
      const classMap = {
        '存款': 'amount-positive',
        '取款': 'amount-negative',
        '转账': 'amount-transfer'
      }
      return classMap[type] || ''
    }

    // 初始化
    onMounted(() => {
      fetchTrades()
    })

    return {
      loading,
      exportLoading,
      detailDialogVisible,
      selectedTrade,
      searchForm,
      dateRange,
      pagination,
      tradeList,
      stats,
      handleSearch,
      handleReset,
      handleRefresh,
      handleView,
      handleDelete,
      handleExport,
      printReceipt,
      handleSizeChange,
      handleCurrentChange,
      formatCardNumber,
      formatDateTime,
      getTradeTypeColor,
      getAmountClass
    }
  }
}
</script>

<style scoped>
.trade-manage {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  transition: transform 0.2s, box-shadow 0.2s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 28px;
  color: white;
}

.stat-card.deposit .stat-icon {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stat-card.withdraw .stat-icon {
  background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.stat-card.transfer .stat-icon {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.stat-card.total .stat-icon {
  background: linear-gradient(135deg, #909399, #b1b3b8);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-amount {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.table-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.card-number {
  font-family: 'Courier New', monospace;
  color: #409eff;
  font-weight: 500;
}

.amount-positive {
  color: #67c23a;
  font-weight: bold;
}

.amount-negative {
  color: #f56c6c;
  font-weight: bold;
}

.amount-transfer {
  color: #409eff;
  font-weight: bold;
}

.balance-amount {
  font-weight: bold;
  color: #67c23a;
}

.trade-detail {
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-card {
  border-radius: 12px;
  border: none;
}
</style> 